<template>
  <div>
    <!-- 表格容器 -->
    <div ref="tableContainer">
      <slot
          name="table"
          :handleRowContextMenu="handleRowContextMenu"
          :currentRow="currentRow"
          :disableExpandRowContext="disableExpandRowContext"
      ></slot>
    </div>

    <!-- Chrome 风格右键菜单 -->
    <div
        v-show="menuVisible"
        ref="contextMenu"
        class="chrome-context-menu"
        :style="{ left: menuX + 'px', top: menuY + 'px' }"
    >
      <div
          v-for="(item, index) in menuItems"
          :key="index"
          class="menu-item"
          :class="{
          'disabled': item.disabled,
          'highlight': item.highlight
        }"
          @click="!item.disabled && handleAction(item.action)"
      >
        <el-icon v-if="item.icon" class="menu-icon">
          <component :is="item.icon" />
        </el-icon>
        <span>{{ item.label }}</span>
        <span v-if="item.shortcut" class="shortcut">{{ item.shortcut }}</span>
        <el-icon v-if="item.children" class="arrow">
          <ArrowRight />
        </el-icon>

        <!-- 子菜单 -->
        <div v-if="item.children" class="submenu">
          <div
              v-for="(subItem, subIndex) in item.children"
              :key="subIndex"
              class="menu-item"
              :class="{ 'highlight': subItem.highlight }"
              @click="handleAction(subItem.action)"
          >
            <el-icon v-if="subItem.icon" class="menu-icon">
              <component :is="subItem.icon" />
            </el-icon>
            <span>{{ subItem.label }}</span>
            <span v-if="subItem.shortcut" class="shortcut">{{ subItem.shortcut }}</span>
          </div>
        </div>
      </div>

      <div v-if="hasDividers" class="menu-divider"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick, markRaw } from 'vue';
import { ArrowRight, View, Edit, DocumentCopy, Upload, Delete, CircleCheck, CircleClose, Message, Refresh } from '@element-plus/icons-vue';

const props = defineProps({
  menuItems: {
    type: Array,
    default: () => [
      { label: '查看详情', action: 'view', icon: markRaw(View) },
      { label: '编辑信息', action: 'edit', icon: markRaw(Edit) },
      { label: '复制内容', action: 'copy', icon: markRaw(DocumentCopy) },
      { label: '粘贴内容', action: 'paste', icon: markRaw(Upload), disabled: true },
      { type: 'divider' },
      { label: '删除记录', action: 'delete', icon: markRaw(Delete) },
      { type: 'divider' },
      {
        label: '状态操作',
        icon: markRaw(CircleCheck),
        children: [
          { label: '激活账户', action: 'activate', icon: markRaw(CircleCheck) },
          { label: '停用账户', action: 'deactivate', icon: markRaw(CircleClose) }
        ]
      },
      { label: '发送邮件', action: 'email', icon: markRaw(Message) },
      { label: '刷新页面', action: 'refresh', icon: markRaw(Refresh) }
    ]
  }
});

const emit = defineEmits(['menu-action', 'row-selected']);

// 菜单状态
const menuVisible = ref(false);
const menuX = ref(0);
const menuY = ref(0);
const currentRow = ref(null);
const contextMenu = ref(null);
const tableContainer = ref(null);

// 检查是否有分隔符
const hasDividers = computed(() => {
  return props.menuItems.some(item => item.type === 'divider');
});

// 新增方法：禁用展开行右键
const disableExpandRowContext = (event) => {
  event.preventDefault();
  event.stopPropagation();
};

// 处理表格行右键点击
const handleRowContextMenu = (row, event) => {
  event.preventDefault();

  // 设置当前行并通知父组件
  currentRow.value = row;
  emit('row-selected', row);

  // 显示菜单
  menuVisible.value = true;
  menuX.value = event.clientX;
  menuY.value = event.clientY;

  // 防止菜单超出屏幕边界
  adjustMenuPosition();

  // 更新菜单项高亮状态
  updateMenuItemsHighlight(row);
};

// 更新菜单项高亮状态
const updateMenuItemsHighlight = (row) => {
  props.menuItems.forEach(item => {
    if (item.highlightCondition) {
      item.highlight = item.highlightCondition(row);
    }

    if (item.children) {
      item.children.forEach(subItem => {
        if (subItem.highlightCondition) {
          subItem.highlight = subItem.highlightCondition(row);
        }
      });
    }
  });
};

// 调整菜单位置
const adjustMenuPosition = () => {
  nextTick(() => {
    if (!contextMenu.value) return;

    const menuWidth = contextMenu.value.offsetWidth;
    const menuHeight = contextMenu.value.offsetHeight;
    const windowWidth = window.innerWidth;
    const windowHeight = window.innerHeight;

    // 防止右侧溢出
    if (menuX.value + menuWidth > windowWidth) {
      menuX.value = windowWidth - menuWidth - 10;
    }

    // 防止底部溢出
    if (menuY.value + menuHeight > windowHeight) {
      menuY.value = windowHeight - menuHeight - 10;
    }
  });
};

// 处理菜单操作
const handleAction = (action) => {
  menuVisible.value = false;
  emit('menu-action', { action, row: currentRow.value });
};

// 点击外部关闭菜单（修改关键点）
const handleClickOutside = (event) => {
  if (menuVisible.value && contextMenu.value && !contextMenu.value.contains(event.target)) {
    menuVisible.value = false;
  }
};

// 滚动时关闭菜单
const handleScroll = () => {
  menuVisible.value = false;
};
// 窗口调整大小时关闭菜单
const handleResize = () => {
  menuVisible.value = false;
};


// 绑定事件监听器
onMounted(() => {
  document.addEventListener('click', handleClickOutside);
  window.addEventListener('scroll', handleScroll);
  window.addEventListener('resize', handleResize);
});

// 清理事件监听器
onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside);
  window.removeEventListener('scroll', handleScroll);
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
/* Chrome 风格右键菜单 */
.chrome-context-menu {
  position: fixed;
  z-index: 9999;
  min-width: 200px;
  background: #fff;
  border-radius: 4px;
  box-shadow:
      0 2px 10px rgba(0, 0, 0, 0.2),
      0 0 0 1px rgba(0, 0, 0, 0.08);
  padding: 6px 0;
  font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  font-size: 13px;
  animation: menu-appear 0.12s ease;
  user-select: none;
}

@keyframes menu-appear {
  from {
    opacity: 0;
    transform: translateY(-5px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.menu-item {
  padding: 6px 12px 6px 32px;
  position: relative;
  cursor: default;
  color: #222;
  transition: background-color 0.1s;
  display: flex;
  align-items: center;
}

.menu-item:hover {
  background-color: #e8f0fe;
  color: #1a73e8;
}

.menu-item:active {
  background-color: #d2e3fc;
}

.menu-item.disabled {
  color: #999;
  cursor: not-allowed;
}

.menu-item.disabled:hover {
  background-color: transparent;
  color: #999;
}

.menu-item.highlight {
  font-weight: 600;
  color: #1a73e8;
}

.menu-icon {
  position: absolute;
  left: 8px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 14px;
}

.shortcut {
  margin-left: auto;
  color: #999;
  font-size: 11px;
  padding-left: 20px;
}

.arrow {
  margin-left: 5px;
  font-size: 12px;
  color: #999;
}

.menu-divider {
  height: 1px;
  background: rgba(0, 0, 0, 0.12);
  margin: 6px 0;
}

/* 子菜单样式 */
.submenu {
  position: absolute;
  top: 0;
  left: 100%;
  min-width: 160px;
  background: #fff;
  border-radius: 4px;
  box-shadow:
      0 2px 10px rgba(0, 0, 0, 0.2),
      0 0 0 1px rgba(0, 0, 0, 0.08);
  padding: 6px 0;
  opacity: 0;
  pointer-events: none;
  transform: translateX(-5px);
  transition: all 0.2s ease;
}

.menu-item:hover > .submenu {
  opacity: 1;
  pointer-events: all;
  transform: translateX(0);
}

.menu-item:hover > .arrow {
  color: #1a73e8;
}
</style>